package idv.nightpig.lab03.one2many;

import java.util.List;

import org.hibernate.SessionFactory;
import org.hibernate.classic.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class One2ManyService {

    private static final Logger LOGGER = LoggerFactory.getLogger(One2ManyService.class);

    @Autowired
    private SessionFactory sessionFactory;

    public void create(Object o) {
        getCurrentSession().save(o);
    }

    public LabGroup findLabGroupById(Long id) {
        return (LabGroup) getCurrentSession().get(LabGroup.class, id);
    }

    private Session getCurrentSession() {
        return sessionFactory.getCurrentSession();
    }

    @SuppressWarnings("unchecked")
    public void method01() {
        List<LabGroup> list = getCurrentSession().createQuery("from LabGroup").list();
        if (list.isEmpty()) {
            LabGroup g1 = new LabGroup();
            g1.setName("g1");
            getCurrentSession().saveOrUpdate(g1);
            for (int i = 0; i < 10; i++) {
                LabUser u1 = new LabUser();
                u1.setAccount("u" + i);
                u1.setGroup(g1);
                getCurrentSession().saveOrUpdate(u1);
            }
        }
    }

    @SuppressWarnings("unchecked")
    public void method02() {
        List<LabGroup> list = getCurrentSession().createQuery("from LabGroup").list();
        for (LabGroup group : list) {
            LOGGER.info(group.getName());
            for (LabUser user : group.getUser()) {
                LOGGER.info("{}, {}", user.getAccount(), user.getGroup().getName());
            }
        }
    }

    @SuppressWarnings("unchecked")
    public void method03() {
        List<LabGroup> list = getCurrentSession().createQuery("from LabGroup").setMaxResults(1).list();
        LabGroup g1 = list.get(0);
        g1.setName("m4");
        for (LabUser user : g1.getUser()) {
            user.setAccount("method03");
        }
        getCurrentSession().saveOrUpdate(g1);
    }

    public void persist(Object o) {
        getCurrentSession().saveOrUpdate(o);
    }

    public void update(Object o) {
        getCurrentSession().update(o);
    }

}
